package security.access;

import java.io.File;
import java.util.Hashtable;
import java.util.Set;

import data.dao.DAO;
import data.dao.SecuredDAO;

class AccessCheckerImpl implements AccessChecker{
	
	private Hashtable<File,Integer> authorizedPaths = new Hashtable<File,Integer>();
	private boolean securedReader;
	
	public AccessCheckerImpl(Hashtable<String,Integer> authorizedPaths, boolean securedReader){
		this.securedReader = securedReader;
		
		Set<String> paths = authorizedPaths.keySet();
		for(String path : paths)
			this.authorizedPaths.put(new File(path), authorizedPaths.get(path));
	}
	
	@Override
	public boolean checkAccess(final String path, final int mode, final DAO dao) {
		if(securedReader && !(dao instanceof SecuredDAO))
			return false;
		
		File toCheck = new File(path);
		
		if(mode == READ && !toCheck.exists())
			return false;
		
		Set<File> paths = authorizedPaths.keySet();
		for(File dir : paths){
			if(toCheck.getAbsolutePath().startsWith(dir.getAbsolutePath())){
				if((mode & authorizedPaths.get(dir)) > 0){
					return true;
				}
			}
		}
		
		return false;
	}

}
